package com.teama4.shop.controller;

import com.alibaba.fastjson.JSON;
import com.teama4.shop.annotation.NeedLogin;
import com.teama4.shop.annotation.SecurityParameter;
import com.teama4.shop.domain.CartSpeCom;
import com.teama4.shop.domain.User;
import com.teama4.shop.domain.UserExample;
import com.teama4.shop.service.CartService;
import com.teama4.shop.service.UserService;
import com.teama4.shop.utils.AesEncryptUtils;
import com.teama4.shop.utils.JSONUtil;
import com.teama4.shop.utils.JavaMailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.*;

import static com.teama4.shop.utils.PhoneCode.getPhonemsg;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private CartService cartService;

    @RequestMapping("logout")
    public void logout(HttpServletResponse resp, HttpServletRequest req) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "ok");
            JSONUtil.printByJSON(resp, map);
        } else {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "fail");
            JSONUtil.printByJSON(resp, map);
        }

    }

    /**
     * 用户实名认证
     *
//     * @param realName 真实姓名
//     * @param idCard   身份证号
     */
    @RequestMapping("userIdCardCommit")
    @SecurityParameter
    @ResponseBody
    @NeedLogin
    public Object userIdCardCommit(HttpServletResponse resp, HttpServletRequest req,@RequestBody String  data ) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String realName = (String) parse.get("realName");
        String idCard= (String) parse.get("idCard");

        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {


            User user = new User();
            user.setId((Integer) session.getAttribute("userId"));
            user.setRealName(realName);
            user.setIdCard(idCard);
            int res = userService.updateByPrimaryKeySelective(user);
            if (res > 0) {
                //如果更新成功
                Map result = new HashMap();
                result.put("result","ok");
                return result;

            } else {
                //如果更新失败
                Map result = new HashMap();
                result.put("result","fail");
                return result;

            }
        } else {
            //如果session获取不到值
            Map result = new HashMap();
            result.put("result","noSession");
            return result;

        }


    }

    /**
     * 用户修改支付密码
     *
//     * @param oldPayPassword
//     * @param newPayPassword
     */
    @NeedLogin
    @RequestMapping("changePayPassword")
    @SecurityParameter
    @ResponseBody
    public Object  changePayPassword(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String oldPayPassword = (String) parse.get("oldPayPassword");
        String newPayPassword= (String) parse.get("newPayPassword");
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null && session.getAttribute("changePayPasswordCount") != null) {
            Integer changePayPasswordCount = (Integer) session.getAttribute("changePayPasswordCount");
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey(userId);
            if (changePayPasswordCount > 1) {


                if (user.getPayPassword().equals(oldPayPassword)) {
                    //验证旧密码正确
                    User userUppdate = new User();
                    userUppdate.setId(userId);
                    userUppdate.setPayPassword(newPayPassword);
                    int res = userService.updateByPrimaryKeySelective(userUppdate);

                    if (res > 0) {
                        //数据库更新成功
                        Map result = new HashMap();
                        result.put("result","ok");
                        return result;


                    } else {
                        //数据库更新失败
                        Map result = new HashMap();
                        result.put("result","fail");
                        return result;

                    }

                } else {
                    changePayPasswordCount -= 1;
                    session.setAttribute("changePayPasswordCount", changePayPasswordCount);
                    //验证旧密码不正确
                    Map result = new HashMap();
                    result.put("result","oldPassError");
                    result.put("passCount",changePayPasswordCount);
                    return result;

                }
            } else {
                Map result = new HashMap();
                result.put("result","fail");
                session.invalidate();
                return result;

            }
        } else {
            //如果session获取不到值
            Map result = new HashMap();
            result.put("result","noSession");
            return result;

        }


    }

    /**
     * 用户设置支付密码
     *
//     * @param payPassword
     */
    @NeedLogin
    @RequestMapping("setPayPassword")
    @SecurityParameter
    @ResponseBody
    public Object setPayPassword(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String payPassword= (String) parse.get("payPassword");
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {
            User user = new User();
            user.setId((Integer) session.getAttribute("userId"));
            //对密码加密
            payPassword = AesEncryptUtils.encrypt(payPassword);
            user.setPayPassword(payPassword);
            int res = userService.updateByPrimaryKeySelective(user);
            if (res > 0) {
                //如果更新成功
                Map result = new HashMap();
                result.put("result","ok");
                return result;

            } else {
                //如果更新失败
                Map result = new HashMap();
                result.put("result","fail");
                return result;
            }
        } else {
            //如果session获取不到值
            Map result = new HashMap();
            result.put("result","noSession");
            return result;
        }


    }

    /**
     * 用户修改邮箱
     *
     * @param resp
     * @param req
//     * @param newEmail
     * @throws UnsupportedEncodingException
     */
    @NeedLogin
    @RequestMapping("ChangeEmail")
    @SecurityParameter
    @ResponseBody
    public Object ChangeEmail(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String newEmail= (String) parse.get("newEmail");
        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {
            User user = new User();
            user.setId((Integer) session.getAttribute("userId"));
            user.setEmail(newEmail);
            int res = userService.updateByPrimaryKeySelective(user);
            if (res > 0) {
                //如果更新成功
                Map result = new HashMap();
                result.put("result","ok");
                return result;

            } else {
                //如果更新失败
                Map result = new HashMap();
                result.put("result","fail");
                return result;

            }
        } else {
            //如果session获取不到值
            Map result = new HashMap();
            result.put("result","noSession");
            return result;
        }


    }

    /**
     * 用户修改手机
     *
     * @param resp
     * @param req
//     * @param newPhone
     * @throws UnsupportedEncodingException
     */
    @NeedLogin
    @RequestMapping("ChangePhone")
    @SecurityParameter
    @ResponseBody
    public Object ChangePhone(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String newPhone  = (String) parse.get("newPhone");

        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null) {
            User user = new User();
            user.setId((Integer) session.getAttribute("userId"));
            user.setPhone(newPhone);
            int res = userService.updateByPrimaryKeySelective(user);
            if (res > 0) {
                //如果更新成功
                Map result = new HashMap();
                result.put("result","ok");
                return result;

            } else {
                //如果更新失败
                Map result = new HashMap();
                result.put("result","fail");
                return result;

            }
        } else {
            //如果session获取不到值
            Map result = new HashMap();
            result.put("result","noSession");
            return result;

        }


    }

    /**
     * 用户修改密码
     *
//     * @param oldPassword 旧密码
//     * @param newPassword 新密码
     */
    @NeedLogin
    @RequestMapping("userChangePassword")
    @SecurityParameter
    @ResponseBody
    public Object userChangePassword(HttpServletResponse resp, HttpServletRequest req,@RequestBody String  data) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String oldPassword = (String) parse.get("oldPassword");
        String newPassword = (String) parse.get("newPassword");

        HttpSession session = req.getSession(false);

        if (session != null && session.getAttribute("userId") != null && session.getAttribute("changePasswordCount") != null) {
            Integer changePasswordCount = (Integer) session.getAttribute("changePasswordCount");
            Integer userId = (Integer) session.getAttribute("userId");
            User user = userService.selectByPrimaryKey(userId);
            if (changePasswordCount > 1) {
                //对密码进行解密
                String userPass = AesEncryptUtils.decrypt(user.getPassword());
                if (userPass.equals(oldPassword)) {
                    //验证旧密码正确
                    User userUppdate = new User();
                    userUppdate.setId(userId);
                    //对密码进行加密
                    newPassword = AesEncryptUtils.encrypt(newPassword);
                    userUppdate.setPassword(newPassword);
                    int res = userService.updateByPrimaryKeySelective(userUppdate);

                    if (res > 0) {
                        //数据库更新成功
                        session.invalidate();
                        Map result = new HashMap();
                        result.put("result","ok");
                        return result;
                    } else {
                        //数据库更新失败
                        Map result = new HashMap();
                        result.put("result","fail");
                        return result;

                    }

                } else {
                    changePasswordCount -= 1;
                    session.setAttribute("changePasswordCount", changePasswordCount);
                    //验证旧密码不正确
                    Map result = new HashMap();
                    result.put("result","oldPassError");
                    result.put("passCount",changePasswordCount);
                    return result;

                }
            } else {
                session.invalidate();
                Map result = new HashMap();
                result.put("result","maxPass");
                return result;
            }
        } else {
            //如果session获取不到值
            Map result = new HashMap();
            result.put("result","noSession");
            return result;

        }
    }


    /**
     * 修改个人资料
     *
     * @param nickName 昵称
     * @param sex      性别
     * @param birthday 生日
     */
    @NeedLogin
    @RequestMapping("editMessage")
    public void editMessage(HttpServletResponse resp, HttpServletRequest req, String nickName, String sex, String birthday) throws UnsupportedEncodingException, ParseException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("userId") != null) {
            Integer id = (Integer) session.getAttribute("userId");
            User user = new User();
            user.setId(id);
            user.setNickname(nickName);
            user.setSex(sex);
            user.setBirthday(birthday);

            int result = userService.updateByPrimaryKeySelective(user);
            //如果更新信息成功
            if (result > 0) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "ok");
                JSONUtil.printByJSON(resp, map);
                //更新失败
            } else {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("result", "fail");
                JSONUtil.printByJSON(resp, map);
            }
            //没有session值
        } else {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("result", "noSession");
            JSONUtil.printByJSON(resp, map);
        }


    }

    /**
     * 登录
     *
//     * @param password 密码
//     * @param account  用户（邮箱或手机号）
     */
    @RequestMapping("userLogin")
    @SecurityParameter
    @ResponseBody
    public Object userLogin(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String password= (String) parse.get("password");
        String account= (String) parse.get("account");

        Integer userId = null;

        String userNickname = null;
        String userHead = null;

        boolean isUser = false;

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andEmailEqualTo(account);
//        criteria.andPasswordEqualTo(password);

        UserExample.Criteria criteria1 = example.createCriteria();
        criteria1.andPhoneEqualTo(account);
//        criteria1.andPasswordEqualTo(password);


        example.or(criteria1);
        List<User> users = userService.selectByExample(example);


        Iterator<User> iterator = users.iterator();
        while (iterator.hasNext()) {
            User next = iterator.next();
            //对密码进行解密
            String oldpassword = AesEncryptUtils.decrypt(next.getPassword());

            if (password.equals(oldpassword) && (account.equals(next.getPhone()) || account.equals(next.getEmail()))) {
                isUser = true;
                userId = next.getId();
                userNickname = next.getNickname();
                userHead = next.getHead();
            }

            break;
        }
        if (isUser) {
            HttpSession session = req.getSession(true);
            session.setAttribute("userId", userId);
            session.setAttribute("userName", userNickname);
            session.setAttribute("userHead", userHead);

            List<CartSpeCom> cartSpeComs = cartService.selectCartByUserIdNOPaging(userId);
            if (cartSpeComs.size() > 0) {
                session.setAttribute("cartIsNull", "notNull");
                int count = 0;
                for (CartSpeCom csc : cartSpeComs) {
                    count += csc.getCommodityCount();
                }
                session.setAttribute("cartAllCount", count);
            } else {
                session.setAttribute("cartIsNull", "null");
                session.setAttribute("cartAllCount", "null");
            }
            //设置修改密码次数
            session.setAttribute("changePasswordCount", 3);
            session.setAttribute("changePayPasswordCount", 3);

            Map result = new HashMap();
            result.put("result","ok");
            return result;

        } else {
            Map result = new HashMap();
            result.put("result","fail");
            return result;

        }


    }

    /**
     * 注册
     *
//     * @param password  密码
//     * @param account   账户（邮箱或手机号）
//     * @param auth_code 验证码
     */
    @RequestMapping("register")
    @SecurityParameter
    @ResponseBody
    public Object register(HttpServletResponse resp, HttpServletRequest req,@RequestBody String  data) throws Exception {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String password = (String) parse.get("password");
        String account = (String) parse.get("account");
        String auth_code = (String) parse.get("auth_code");

        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute(account + "auth_code") != null) {
            String sessionAccount = (String) session.getAttribute(account + "account");
            String sessionAuthCode = (String) session.getAttribute(account + "auth_code");
            String account_type = (String) session.getAttribute(account + "account_type");

            if (sessionAccount.equals(account) && sessionAuthCode.equals(auth_code)) {
                User insUser = new User();

                //使用ASE算法对密码进行加密

//                byte[] password64= AesEncryptUtils.encrypt(password, Encrypt.AESprivateKey);
                password = AesEncryptUtils.encrypt(password);
                if (account_type.equals("email")) {
                    insUser.setEmail(account);
                    insUser.setPassword(password);
                } else if (account_type.equals("phone")) {
                    insUser.setPhone(account);
                    insUser.setPassword(password);
                }
                insUser.setHead("b8ccf929-e0df-4088-b7c6-a91e9a474bab.jpg");
                int res = userService.insertSelective(insUser);
                if (res > 0) {
                    Map result = new HashMap();
                    result.put("result","ok");
                    return result;

                } else {
                    //数据库更新失败
                    Map result = new HashMap();
                    result.put("result","fail");
                    return result;

                }
            } else {
                //如果验证码或账户不正确
                Map result = new HashMap();
                result.put("result","noCode");
                return result;

            }
            //如果session为空
        } else {
            Map result = new HashMap();
            result.put("result","noSession");
            return result;
        }


    }

    /**
     * 检查账户是否存在
     *
     * @param account
     * @return
     */
    private boolean isHaveUser(String account) {
        UserExample example = new UserExample();
        List<User> allUsers = userService.selectByExample(example);
        Iterator<User> allusersIterator = allUsers.iterator();
        while (allusersIterator.hasNext()) {
            User next = allusersIterator.next();
            if ((next.getEmail() != null && next.getEmail().equals(account)) || (next.getPhone() != null && next.getPhone().equals(account))) {
                return true;
            }
        }
        return false;
    }


    /**
     * 注册发送邮箱验证码
     *
//     * @param email
     */
    @NeedLogin
    @RequestMapping("registerEmailAuthCode")
    @SecurityParameter
    @ResponseBody
    public Object registerEmailAuthCode(HttpServletRequest req, HttpServletResponse resp, @RequestBody String  data) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String email  = (String) parse.get("email");

        //查看是否存在账户
        if (isHaveUser(email)) {
            Map result = new HashMap();
            result.put("result","exit");
            return result;

        } else {
            //随机六位数字作为验证码
            Random rm = new Random();
            String auth_code = "";
            for (int i = 0; i < 6; i++) {
                int num = rm.nextInt(10) + 48;
                auth_code += (char) num;
            }
            //发送邮件
            int res = JavaMailUtils.sendEmail(new String[]{
                    email //这里就是一系列的收件人的邮箱了
            }, "淘淘购物邮箱验证", "欢迎您注册淘淘购物，您的验证码是 <br />" + auth_code);
            if (res == 1) {
                //设置session的值
                HttpSession session = req.getSession(true);
                session.setAttribute(email + "auth_code", auth_code);
                session.setAttribute(email + "account", email);
                session.setAttribute(email + "account_type", "email");
                session.setMaxInactiveInterval(5 * 60);
                //返回值
                Map result = new HashMap();
                result.put("result","ok");
                return result;

                //如果发送成功

                //如果发送验证码不成功
            } else {
                Map result = new HashMap();
                result.put("result","fail");
                return result;
            }
        }
    }

    /**
     * 用户修改邮箱第一步：已有邮箱验证
     *
//     * @param code
     */
    @NeedLogin
    @RequestMapping("ChangeEmailCheckCode")
    @SecurityParameter
    @ResponseBody
    public Object ChangeEmailCheckCode(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String code = (String) parse.get("code");

        HttpSession session = req.getSession(false);
        if (session != null) {

            if (session.getAttribute("changeEmailAuthCode") != null && session.getAttribute("changeEmailAuthCodeCount") != null) {
                Integer changeEmailAuthCodeCount = (Integer) session.getAttribute("changeEmailAuthCodeCount");
                if (changeEmailAuthCodeCount > 1) {
                    if (code.equals(session.getAttribute("changeEmailAuthCode"))) {

                        session.setAttribute("changeEmailAuthCode", null);
                        session.setAttribute("changeEmailAuthCodeCount", null);

                        Map result = new HashMap();
                        result.put("result","ok");
                        return result;
                    } else {
                        changeEmailAuthCodeCount -= 1;
                        session.setAttribute("changeEmailAuthCodeCount", changeEmailAuthCodeCount);

                        Map result = new HashMap();
                        result.put("result","codeError");
                        result.put("changeEmailAuthCodeCount",changeEmailAuthCodeCount);
                        return result;
                    }
                } else {

                    session.setAttribute("changeEmailAuthCode", null);
                    session.setAttribute("changeEmailAuthCodeCount", null);

                    Map result = new HashMap();
                    result.put("result","maxCode");
                    return result;
                }


            } else {

                Map result = new HashMap();
                result.put("result","noCode");
                return result;
            }
        } else {

            Map result = new HashMap();
            result.put("result","noSession");
            return result;
        }
    }

    /**
     * 修改邮箱发送邮箱验证码
     *
//     * @param email
//     * @param type
     */
    @NeedLogin
    @RequestMapping("changeEmailAuthCode")
    @SecurityParameter
    @ResponseBody
    public Object changeEmailAuthCode(HttpServletRequest req, HttpServletResponse resp,@RequestBody String  data) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String email = (String) parse.get("email");
        String type = (String) parse.get("type");

        //查看是否存在账户
        if (type.equals("old") && !isHaveUser(email)) {
            Map result = new HashMap();
            result.put("result","unexit");
            return result;
        } else if (type.equals("new") && isHaveUser(email)) {

            Map result = new HashMap();
            result.put("result","exit");
            return result;
        } else {
            //随机六位数字作为验证码
            Random rm = new Random();
            String auth_code = "";
            for (int i = 0; i < 6; i++) {
                int num = rm.nextInt(10) + 48;
                auth_code += (char) num;
            }
            //发送邮件
            int res = JavaMailUtils.sendEmail(new String[]{
                    email //这里就是一系列的收件人的邮箱了
            }, "淘淘购物邮箱验证", "淘淘购修改邮箱，您的验证码是 <br />" + auth_code +
                    "<br/> <span style='color:red'>您正在进行修改邮箱操作，若不是您本人操作，请尽快联系管理员！</span>");
            if (res == 1) {
                //设置session的值
                HttpSession session = req.getSession(false);
                session.setAttribute("changeEmailAuthCode", auth_code);
                session.setAttribute("changeEmailAuthCodeCount", 3);

                //返回值
                Map result = new HashMap();
                result.put("result","ok");
                return result;
                //如果发送成功

                //如果发送验证码不成功
            } else {
                Map result = new HashMap();
                result.put("result","fail");
                return result;
            }
        }
    }

    /**
     * 用户修改手机号第一步：已有手机号验证
     *
//     * @param code
     */
    @NeedLogin
    @RequestMapping("ChangePhoneCheckCode")
    @SecurityParameter
    @ResponseBody
    public Object ChangePhoneCheckCode(HttpServletResponse resp, HttpServletRequest req, @RequestBody String  data) throws UnsupportedEncodingException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String code  = (String) parse.get("code");
        HttpSession session = req.getSession(false);
        if (session != null) {

            if (session.getAttribute("changePhoneAuthCode") != null && session.getAttribute("changePhoneAuthCodeCount") != null) {
                Integer changePhoneAuthCodeCount = (Integer) session.getAttribute("changePhoneAuthCodeCount");
                if (changePhoneAuthCodeCount > 1) {
                    if (code.equals(session.getAttribute("changePhoneAuthCode"))) {
                        session.setAttribute("changePhoneAuthCode", null);
                        session.setAttribute("changePhoneAuthCodeCount", null);

                        Map result = new HashMap();
                        result.put("result","ok");
                        return result;
                    } else {
                        changePhoneAuthCodeCount -= 1;
                        session.setAttribute("changePhoneAuthCodeCount", changePhoneAuthCodeCount);

                        Map result = new HashMap();
                        result.put("result","codeError");
                        result.put("changePhoneAuthCodeCount",changePhoneAuthCodeCount);
                        return result;
                    }
                } else {
                    session.setAttribute("changePhoneAuthCode", null);
                    session.setAttribute("changePhoneAuthCodeCount", null);

                    Map result = new HashMap();
                    result.put("result","maxCode");
                    return result;
                }


            } else {

                Map result = new HashMap();
                result.put("result","noCode");
                return result;
            }
        } else {

            Map result = new HashMap();
            result.put("result","noSession");
            return result;
        }
    }

    /**
     * 修改手机发送邮箱验证码
     *
//     * @param phone
//     * @param type
     */
    @NeedLogin
    @RequestMapping("changePhoneAuthCode")
    @SecurityParameter
    @ResponseBody
    public Object changePhoneAuthCode(HttpServletRequest req, HttpServletResponse resp, 	@RequestBody String  data) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map parse = JSON.parseObject(data,Map.class);
        String phone= (String) parse.get("phone");
        String type= (String) parse.get("type");
        //查看是否存在账户
        if (type.equals("old") && !isHaveUser(phone)) {

            Map result = new HashMap();
            result.put("result","unexit");
            return result;
        } else if (type.equals("new") && isHaveUser(phone)) {

            Map result = new HashMap();
            result.put("result","exit");
            return result;
        } else {
            //随机六位数字作为验证码
            Random rm = new Random();
            String auth_code = "";
            for (int i = 0; i < 6; i++) {
                int num = rm.nextInt(10) + 48;
                auth_code += (char) num;
            }
            //发送验证码
            String res = getPhonemsg(phone, auth_code);
            if (res.equals("ok")) {
                //设置session的值
                HttpSession session = req.getSession(false);
                session.setAttribute("changePhoneAuthCode", auth_code);
                session.setAttribute("changePhoneAuthCodeCount", 3);

                //返回值

                Map result = new HashMap();
                result.put("result","ok");
                return result;
                //如果发送成功

                //如果发送验证码不成功
            } else {
                Map result = new HashMap();
                result.put("result",res);
                return result;
            }
        }
    }

    /**
     * 注册发送手机验证码
     *
//     * @param phone
     */
    @NeedLogin
    @RequestMapping("registerPhoneAuthCode")
    @SecurityParameter
    @ResponseBody
    public Object registerPhoneAuthCode(HttpServletRequest req, HttpServletResponse resp, @RequestBody String  data) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Map parse = JSON.parseObject(data,Map.class);
        String phone = (String) parse.get("phone");

        //查看是否存在账户
        if (isHaveUser(phone)) {

            Map result = new HashMap();
            result.put("result","exit");
            return result;
        } else {
            //随机六位数字作为验证码
            Random rm = new Random();
            String auth_code = "";
            for (int i = 0; i < 6; i++) {
                int num = rm.nextInt(10) + 48;
                auth_code += (char) num;
            }
            //发送邮件
            String res = getPhonemsg(phone, auth_code);
            if (res.equals("ok")) {
                //设置session的值
                HttpSession session = req.getSession(true);
                session.setAttribute(phone + "auth_code", auth_code);
                session.setAttribute(phone + "account", phone);
                session.setAttribute(phone + "account_type", "phone");
                session.setMaxInactiveInterval(5 * 60);
                //返回值

                Map result = new HashMap();
                result.put("result","ok");
                return result;
                //如果发送成功

                //如果发送验证码不成功
            } else {

                Map result = new HashMap();
                result.put("result",res);
                return result;
            }
        }
    }

}
